#ifndef LISSERVER_H
#define LISSERVER_H

#include <QObject>
#include <QTimer>
#include <QRandomGenerator>

#include "serial.h"
#include "ASTM/HeaderRecord.h"
#include "ASTM/RequestRecord.h"

class LISServer : public Serial
{
    Q_OBJECT
public:
    explicit LISServer(const QString &port, QObject *parent = nullptr);

    bool checkRxData(const QByteArray &frame) const;
    QByteArray dataToFrame(const QByteArray &data) const {
        return ASTM::dataToFrame(data);
    }

    QByteArray dataFromeFrame(const QByteArray &frame) const {
        return ASTM::dataFromeFrame(frame);
    }

    bool autoOpenLISPort();
    void addRequest(const RequestRecord &request);

    bool sendAndDebug(char byte);
    // bool sendAndDebug(const QByteArray &data);
    bool sendFrame(const QByteArray &data);

signals:

private:
    QRecursiveMutex mutex;
    // QByteArray txBuf;
    QList<RequestRecord> requests;
    QTimer ackTimer;
    QRandomGenerator random;
    int orderIndex = 0;

    void onRequestIn(const QStringList &records);
    QString buildFrame(HeaderRecord::MsgType type, const QString &record) const;
    void reply(const RequestRecord &request);
    void startReply();

private slots:
    void onFrameIn(const QByteArray &frame);
    void onAckTimeout();
};

#endif // LISSERVER_H
